<template>
	<view class="w-flex-col w-justify-start page">
		<view class="adContainer">
				<ad unit-id="adunit-efa31e89675c80f3" ad-type="video" ad-theme="white" bindload="adLoad" binderror="adError" bindclose="adClose"></ad>
		</view>
		<view class="w-flex-col section">
			<view class="w-flex-col section_2 space-y-22">
				<view class="w-flex-row w-justify-between w-items-start">
					<view class="w-flex-row w-items-start space-x-8">
						<image class="image img" :src="wifi.get_user.head_img" />
						<view class="w-flex-col w-items-start group_2 space-y-16">
							<text class="font_1 text">{{wifi.store}}</text>
							<text class="font_1 text_2">{{wifi.account}}</text>
						</view>
					</view>
					<view class="w-flex-col w-items-center group space-y-4">
						<button class="btn" plain open-type="share">
							<image class="image image_3" src="/static/connect_wifi/share.png" />
							<text class="font_2 fontshare">分享</text>
						</button>
					</view>
				</view>
				<view class="w-flex-row w-justify-around group_3">
					<text class="font_2">一键安全连接</text>
					<text class="font_2">无需告知密码</text>
					<text class="font_2">安全防蹭网</text>
				</view>
			</view>
			<image class="w-self-center image image_2"
				src="/static/connect_wifi/9f5f9d2ca0f107f5b97358724f707781.gif" />
			<view class="w-flex-col w-justify-start w-items-center w-self-center button">
				<text class="font_2 text_3" v-show="linking">正在连接</text>
				<text class="font_2 text_3" v-show="!linking && is_linked">已连接</text>
				<text class="font_2 text_3" @tap="advSetConnect" v-show="!linking && !is_linked">一键安全连接WIFI</text>
			</view>
		</view>
	</view>
</template>

<script>
	const errCodeMap = {
		'12000': 'WIFI未初始化',
		'12001': '系统不支持',
		'12002': '密码错误',
		'12003': '连接超时',
		'12004': '重复连接Wi-Fi',
		'12005': '未打开Wi-Fi开关',
		'12006': '未打开GPS定位开关',
		'12007': '用户拒绝授权链接Wi-Fi',
		'12008': '无效SSID',
		'12009': '系统运营商配置拒绝连接Wi-Fi',
		'12010': '系统错误',
		'12011': '应用在后台无法配置Wi-Fi',
		'12014': '密码错误',
		'1505005': '密码错误',
	}
	export default {
		components: {},
		data() {
			return {
				linking: false,
				is_linked: false,
				wifi: [],
				id: 0,
				isLoading: false,
				interstitialAd: null
			};
		},

		adLoad() {
			console.log('视频广告 广告加载成功')
		},
		adError(err) {
			console.error('视频广告 广告加载失败', err)
		},
		adClose() {
			console.log('视频广告 广告关闭')
		},

		onLoad(e) {
			if (e.hasOwnProperty('scene')) {
				this.id = e.scene
				this.getWifiOne()
			}
			// 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
			// 在页面onLoad回调事件中创建插屏广告实例
			if (wx.createInterstitialAd) {
				this.interstitialAd = wx.createInterstitialAd({
					adUnitId: 'adunit-959c3b660e34c7f3'
				})
				this.interstitialAd.onLoad(() => {})
				this.interstitialAd.onError((err) => {
					console.error('插屏广告加载失败', err)
				})
				this.interstitialAd.onClose(() => {})
			}
			// 调试用
			// this.id = 54
			// this.getWifiOne()
		},

		onShow() {
			uni.login({
				provider: 'weixin',
				success: async (res) => {
					// console.log('登录获取code', res.code);
					if (res.errMsg == 'login:ok') {
						await this.loginAuth({
							userProfile: [],
							code: res.code,
						});
					}
				},
			});
		},

		methods: {
			connect(maunal = false) {
				// 判断接口数据是否加载
				if (this.wifi.length <= 0) {
					return uni.showToast({
						icon: 'none',
						title: '数据未加载，请重新点击连接'
					})
				}

				// 连接或者已经连上
				if (this.linking || this.is_linked) {
					return uni.showToast({
						icon: 'none',
						title: '正在连接或已连接成功'
					})
				}
				uni.showLoading({
					mask: true,
					title: '正在连接'
				})
				this.linking = true;
				let maunalRetry = false;
				// console.log('connectwifi', maunalRetry)
				uni.connectWifi({
					SSID: this.wifi.account,
					password: this.wifi.pass,
					maunal: maunal,
					success: (res) => {
						// console.log('链接wifi结果', res, maunalRetry);
						this.checkLink(maunal, maunalRetry);
					},
					fail: (err) => {
						// 初始化数据
						this.linking = false
						this.is_linked = false
						this.checkLink(maunal, maunalRetry);
						// console.log(err, err.errMsg, errCodeMap['' + err.errCode])
						uni.showToast({
							icon: "none",
							title: errCodeMap['' + err.errCode] || '连接失败',
						})
					},
					complete: () => {
						// console.log('链接wificomplete结果', maunalRetry);
					}
				})
			},
			// 检测是否连接
			checkLink(maunal, maunalRetry) {
				uni.startWifi({
					success: () => {
						uni.getConnectedWifi({
							success: ({
								wifi
							}) => {
								// console.log('是否已链接', wifi.SSID, this.wifi.account);
								this.is_linked = (wifi.SSID === this.wifi.account)
								let success = this.is_linked
								let systemInfo = this.getSysOs()
								if(systemInfo.isAndroid10laest){
									success = false;
									maunalRetry = true;
									maunal = true;
									this.handelSAndroid10(success, maunalRetry, maunal)
								}else{
									maunalRetry = !maunal && systemInfo.isAndroid10laest
									// console.log('complete', maunal, systemInfo.isAndroid10laest, success, maunalRetry)
									// 不管什么版本，直接连接成功
									this.connectSuccess(success, maunalRetry)
									// console.log('android 10以上手机第一次自动连接失败时需要手动连接')
									//android 10以上手机第一次自动连接失败时需要手动连接
									this.handelSAndroid10(success, maunalRetry, maunal)
								}
								// console.log('没有连接成功，也不是版本问题')
								this.connectFail(success, maunalRetry)
								// 没有连接成功，也不是版本问题
							},
							fail: (err) => {
								// console.log(err)
								this.linking = false
								this.is_linked = false
								return uni.showToast({
									icon: 'none',
									title: '没有找到wifi/密码错误',
									duration: 5000
								})
							},
						})
					},
					fail: (err) => {
						// console.log('打开wifi失败', err)
						return uni.showToast({
							icon: 'none',
							title: '打开wifi失败'
						})
					}
				})
				// console.log('return', this.is_linked)
			},
			getWifiOne() {
				this.$http.get('wifione', {
					params: {
						id: this.id
					}
				}).then(res => {
					let one = res.data.data
					this.wifi = one
					// 复制抖音链接
					uni.setClipboardData({
						data: this.wifi.douyin_url,
						showToast:false,
						success: function () {
							uni.hideToast()
							// console.log('success');
						}
					});
					// console.log(this.wifi.account, this.wifi.pass)
					// console.log('end')
				}).catch(err => {

				})
			},
			getSysOs() {
				let systemInfo = uni.getSystemInfoSync();
				systemInfo.navbarHeight = systemInfo.platform == 'ios' ? 44 : 48;
				systemInfo.isIOS = systemInfo.system?.toLowerCase().indexOf('ios') > -1;
				systemInfo.isAndroid = systemInfo.system?.toLowerCase().indexOf('android') > -1;
				if (systemInfo.isAndroid) {
					try {
						systemInfo.isAndroid10laest = Number(systemInfo.osVersion) >= 10
					} catch (err) {
						systemInfo.isAndroid10laest = true;
					}
				}
				// console.log('系统信息',systemInfo)
				return systemInfo
			},
			setConnent() {
				// 初始化数据
				this.linking = false
				this.is_linked = false
				uni.startWifi({
					success: () => {
						// console.log('打开wifi成功')
						uni.getConnectedWifi({
							success: ({
								wifi
							}) => {
								// console.log('点击按钮')
								this.is_linked = (wifi.SSID === this.wifi.account)
								if (this.is_linked) {
									return uni.showToast({
										icon: 'none',
										title: '连接成功'
									})
								} else {
									this.connect(); //第一次自动连接
								}
							},
							fail: (err) => {
								this.connect(); //第一次自动连接
							}
						})
					},
					fail: (err) => {
						// console.log('打开wifi失败', err)
						return uni.showToast({
							icon: 'none',
							title: '打开wifi失败'
						})
					}
				});
			},
			// 连接成功
			connectSuccess(success, maunalRetry) {
				if (success) {
					this.linking = false;
					uni.hideLoading();
					return uni.showToast({
						icon: 'none',
						title: '连接成功'
					})
				}
				if (success || !maunalRetry) {
					// console.log('complete3', success, maunalRetry)
					this.linking = false;
					uni.hideLoading();
					if (success) {
						return uni.showToast({
							icon: 'none',
							title: '连接成功'
						})
					} else {
						return uni.showModal({
							title: '连接WIFI',
							confirmText: '跳转',
							content: `密码已复制,请手动选中【${this.wifi.account}】粘贴密码连接`,
							success: ({
								confirm
							}) => {
								if (confirm) {
									uni.setClipboardData({
										data: this.wifi.pass,
										success() {
											uni.startWifi({
												success: () => {
													// console.log('打开wifi成功')
													this.connect(true)
												},
												fail: (err) => {
													// console.log('打开wifi失败', err)
												}
											});
										}
									})
								}
							}
						})
					}
				}
			},
			// android 10版本
			handelSAndroid10(success, maunalRetry, maunal) {
				var that = this
				// 没有成功，没有跳转并且安卓10，没有跳转
				if (!success && maunalRetry && !maunal) {
					that.linking = false;
					uni.hideLoading();
					return uni.showModal({
						title: '连接WIFI',
						confirmText: '跳转',
						content: `密码已复制,请手动选中【${that.wifi.account}】粘贴密码连接`,
						success: ({
							confirm
						}) => {
							if (confirm) {
								uni.setClipboardData({
									data: that.wifi.pass,
									success() {
										uni.startWifi({
											success: () => {
												// console.log('打开wifi成功')
												that.connect(true)
											},
											fail: (err) => {
												// console.log('打开wifi失败', err)
											}
										});
									}
								})
							}
						}
					})
				}
			},
			connectFail(success, maunalRetry) {
				var that = this
				if (!success && !maunalRetry) {
					that.linking = false;
					uni.hideLoading();
					return uni.showModal({
						title: '连接WIFI',
						confirmText: '跳转',
						content: `密码已复制,请手动选中【${that.wifi.account}】粘贴密码连接`,
						success: ({
							confirm
						}) => {
							if (confirm) {
								uni.setClipboardData({
									data: that.wifi.pass,
									success() {
										uni.startWifi({
											success: () => {
												// console.log('打开wifi成功')
												that.connect(true)
											},
											fail: (err) => {
												// console.log('打开wifi失败', err)
											}
										});
									}
								})
							}
						}
					})
				}
			},
			showAd() {
				// 在适合的场景显示插屏广告
				if (this.interstitialAd) {
					this.interstitialAd.show().catch((err) => {
						console.error('插屏广告显示失败', err)
					})

					this.addAdvLog()
				}
			},
			advSetConnect() {
				// 屏蔽广告时候给收益
				// this.addAdvLog()
				// 暂时屏蔽广告
				this.showAd()
			},
			addAdvLog() {
				this.$http.post('addWifiAdvLog', {
					wid: this.id
				}).then(res => {
					if (res.data.code) {
						this.setConnent()
					}
				}).catch(err => {

				})
			},
			loginAuth(data) {
				// console.log(data)
				this.$http.post('wuserlogin', {
					code: data.code
				}).then(res => {
					uni.setStorageSync('token', res.data.data.access_token)
					this.token = res.data.data.access_token
					this.getUser()
				}).catch(err => {

				})
			},
			getUser() {
				this.$http.get('user', {}).then(res => {
					this.user = res.data.data
					uni.setStorageSync('user', res.data.data)
				}).catch(err => {

				})
			},
		},
	};
</script>

<style scoped lang="scss">
	.page {
		padding-top: 0rpx;
		background-color: #f9f9f9;
		width: 100%;
		overflow: hidden;
		height: 100vh;

		.section {
			padding: 15rpx 30rpx 192rpx 30rpx;
			background-color: #f9f9f9;

			.section_2 {
				padding: 16rpx 20rpx 32rpx 34rpx;
				background-color: #fff;
				border-radius: 20rpx;

				.space-x-8 {

					&>view:not(:first-child),
					&>text:not(:first-child),
					&>image:not(:first-child) {
						margin-left: 16rpx;
					}

					.group_2 {
						margin-top: 28rpx;

						.font_1 {
							font-size: 30rpx;
							font-family: SourceHanSansCN;
							color: #000000;
						}

						.text {
							line-height: 37rpx;
						}

						.text_2 {
							margin-left: 8rpx;
							line-height: 30rpx;
							font-size: 28rpx;
						}
					}

					.space-y-16 {

						&>view:not(:first-child),
						&>text:not(:first-child),
						&>image:not(:first-child) {
							margin-top: 32rpx;
						}
					}
				}

				.group {
					margin-top: 12rpx;
					margin-right: -60rpx;
				}

				.space-y-4 {

					&>view:not(:first-child),
					&>text:not(:first-child),
					&>image:not(:first-child) {
						margin-top: 8rpx;
					}
				}

				.group_3 {
					padding-left: 0rpx;
					padding-right: 0rpx;
				}
			}

			.space-y-22 {

				.btn {
					background-color: #fff;
					border: none;
					height: 120rpx;

					.fontshare {
						position: relative;
						top: 50rpx;
						right: 50rpx;
					}
				}

				&>view:not(:first-child),
				&>text:not(:first-child),
				&>image:not(:first-child) {
					margin-top: 60rpx;
				}
			}

			.image {
				width: 100rpx;
				height: 100rpx;
			}

			.img {
				margin-top: 20rpx;
				border-radius: 50%;
			}

			.image_3 {
				width: 50rpx;
				height: 50rpx;
			}

			.image_2 {
				margin-top: 120rpx;
				width: 200rpx;
				height: 200rpx;
			}

			.button {
				margin-top: 102rpx;
				padding: 20rpx 0;
				background-color: #347bf1;
				border-radius: 10rpx;
				width: 392rpx;

				.text_3 {
					color: #ffffff;
				}
			}

			.font_2 {
				font-size: 28rpx;
				font-family: SourceHanSansCN;
				line-height: 26rpx;
				color: #000000;
			}
		}
	}
</style>
